package cn.jbit.test.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * 源码学院只为培养优秀的bat程序员而生
 *
 * @author 学员张在成
 * @data 2021/6/27
 */
public class NioTestServer {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
        //绑定端口号
        serverSocketChannel.socket().bind(new InetSocketAddress(8084),1024);
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //初始化通道
        SocketChannel socketChannel=null;

        while (true) {
            //轮询接收客户端的连接
            socketChannel = serverSocketChannel.accept();
            try {
                //进行数据的读
                System.out.println("进行数据的读：");
                ByteBuffer buffer=ByteBuffer.allocate(1024);
                      int read = socketChannel.read(buffer);
                if (read>0) {
                    buffer.flip();
                    byte[] byte1 = new byte[buffer.remaining()];
                    buffer.get(byte1);
                    System.out.println("receive client data is:" + new String(byte1, "UTF-8"));
                }
            }catch (Exception e){
                e.printStackTrace();
                System.out.println("缓存区数据为空");
            }

            //响应客户端
            Scanner sc=new Scanner(System.in);
            String next = sc.next();
            byte[] bytes=next.getBytes();
            //进行事件的读写
            ByteBuffer  byteBuffer=ByteBuffer.allocate(bytes.length);
            byteBuffer.put(bytes);
            //读写模式反转
            byteBuffer.flip();
            //写书数据
            socketChannel.write(byteBuffer);
        }
    }
}
